<template>
    <div class="container">
        <div class="header">
            <el-image :src="imageUrl" style="width:100%;height:400px"></el-image>
            <el-upload class="uploadbackground" action="http://118.190.158.210:88/api/ossimage/fbk/oss/upload"
                :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <!-- <img v-if="imageUrl" src="#" class="avatar"> -->
                <i class="el-icon-plus avatar-uploader-icon">点我更新背景图片</i>
            </el-upload>
        </div>
        <div class="main">
            <el-form ref="form" :rules="rules" :model="userForm" label-width="80px" size="mini">
                <el-form-item label="用户名">
                    <el-input v-model="userForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="userForm.password" :disabled="isDisabled"></el-input>
                    <el-button type="primary" @click="ensurePasswordShow = true">是否要修改密码</el-button>
                </el-form-item>
                <el-form-item label="请输入之前的密码" v-if="ensurePasswordShow">
                    <el-input v-model="userForm.ensurePassword"></el-input>
                    <el-button type="primary" @click="getMyPassword">确认密码</el-button>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话号码" prop="phoneNumber">
                    <el-input v-model="userForm.phoneNumber"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-input v-model="userForm.sex"></el-input>
                </el-form-item>
                <el-form-item label="简介">
                    <el-input v-model="userForm.introduce"></el-input>
                </el-form-item>
                <el-form-item size="large">
                    <el-button type="primary" @click="onSubmit">立即更新</el-button>
                    <el-button>取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>

</template>

<script>
import api from '../utils/api';
import { Message } from 'element-ui';
import login from '../utils/login'
import { isEmail, isPhone } from '../utils/validate'
import {getUserId,getUserName,getEmail,getIntroduce,getSex,getPhoneNumber,
        setUserName,setEmail,setIntroduce,setSex,setPhoneNumber
} from '@/utils/auth'
export default {
    data() {
        const validatoremail = (rule, value, callback) => {
            if (!isEmail(value)) {
                callback(new Error('邮箱格式错误'))
            } else {
                callback()
            }
        };
        const validatorPhonenumber = (rule, value, callback) => {
            if (isPhone(value)) {
                callback(new Error('手机格式错误'))
            } else {
                callback()
            }
        };
        return {
            ifNotUpdateImg:'',
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            ensurePasswordShow: false,
            isDisabled: true,
            imageUrl:'',
            userForm: {
                username: '',
                password: '',
                ensurePassword: '',
                email: '',
                phoneNumber: '',
                sex: '',
                introduce: '',
                dialogImageUrl: '',
                dialogVisible: false
            },
            action: process.env.VUE_APP_BASE_API_UPLOAD + `/blogimage/fbk/oss/upload`,
            rules: {
                email: [
                    { required: true, trigger: 'blur', validator: validatoremail }
                ],
                phoneNumber: [
                    { required: true, trigger: 'blur', validator: validatorPhonenumber }
                ]
            }
        }
    },
    components: {
    },
    computed: {
    },
    created() {
        var username = getUserName()
        if (username == ""||username==null||username==undefined) {
            this.getUserInfo()
        }
        this.getBackGroundImg()
    },
    mounted() {
        this.$nextTick(() => {
            this.getUser()
        })
    },
    methods: {
        getMyPassword() {
            var userId = getUserId()
            var password = this.userForm.ensurePassword
            if (userId > 0 && password != '') {
                login.byPasswordGetPassword(password, userId).then(res => {
                    if (res.data != null) {
                        this.isDisabled = false
                        this.userForm.password = res.data
                        this.ensurePasswordShow = false
                        Message({
                            type: 'success',
                            message: '获取密码成功'
                        })
                    } else {
                        this.userForm.password = ''
                        this.userForm.ensurePassword = ''
                        Message({
                            type: 'error',
                            message: '获取密码失败,请再次校验密码'
                        })
                    }
                })
            } else {
                Message({
                    type: 'error',
                    message: '用户信息错误，请稍后再试'
                })
            }
        },
        getUserInfo() {
            this.$store.dispatch('GetInfo').then(() => {
            })
        },
        getBackGroundImg() {
            var userId =getUserId()
            if (userId == '') {
                userId = -1
            }
            api.GetBackGroundImg(userId).then(res => {
                if (res.data) {
                    this.imageUrl=res.data
                    return res.data
                } else {
                    Message({
                        type: 'error',
                        message: '获取背景图片失败'
                    })
                }
            })
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            console.log(res.data)
            if (res.data !== null) {
                this.$message({
                    type: 'success',
                    message: '上传成功'
                })
                var userId =getUserId()
                if (userId == '') {
                    userId = -1
                }
                api.SaveBackGroundimg(userId, res.data).then(res => {
                    console.log(res.data)
                })
                this.imageUrl = res.data
                this.$store.dispatch('uploadBackgroundImg', res.data)
            } else {
                this.$message({
                    type: 'error',
                    message: '上传失败'
                })
            }
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        onSubmit() {
            console.log('form是', this.userForm)
            var userId = this.getUserId()
            if (userId == '') {
                userId = -1
            }
            this.$refs.form.validate(validate => {
                if(validate){
                login.updateMyselfInformation(
                    userId, this.userForm.username,
                    this.userForm.password,
                    this.userForm.email,
                    this.userForm.phoneNumber,
                    this.userForm.sex,
                    this.userForm.introduce
                ).then(res => {
                    if (res.data) {
                        setUserName( this.userForm.username)
                        setEmail(this.userForm.email)
                        setPhoneNumber(  this.userForm.phoneNumber)
                        setSex(  this.userForm.sex)
                        setIntroduce( this.userForm.introduce)
                        Message({
                            type: 'success',
                            message: '更新成功'
                        })
                    } else {
                        Message({
                            type: 'error',
                            message: '更新失败。请稍后再试'
                        })
                    }
                })
                }else{
                    Message({
                        type:'error',
                        message:'提交格式错误'
                    })
                }
            })
        
        },
        getUser() {
            this.userForm.username =getUserName()
            this.userForm.email =getEmail()
            this.userForm.sex =getSex()
            this.userForm.introduce =getIntroduce()
            this.userForm.phoneNumber =getPhoneNumber()
        },
        getUserInfo() {
            this.$store.dispatch('GetInfo').then(() => {
            })
        },
    }
}
</script>

<style scoped>
.container {
    position: relative;
    margin: 0 auto;
    width: 60%;
}

.header {
    width: 100%;
    height: 300px;
}

.uploadbackground {
    position: absolute;
    left: 10px;
    top: 10px;
}

.main {
    margin-top: 200px;
}
</style>